package com.hedd.shop.utils;

import com.hedd.shop.pojo.entity.GoodInfo;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Jsoup {


    public static List goodInfos(String url) throws IOException {
        ArrayList<GoodInfo> goodInfos = new ArrayList<GoodInfo>();
//        String url = "https://search.jd.com/Search?keyword=%E7%B2%BE%E5%93%81&enc=utf-8&wq=jing%20p&pvid=91a6edbcd22a45e3902f3059064720b0";
        Document parse = org.jsoup.Jsoup.parse(new URL(url), 30000);
        Element goodsList = parse.getElementById("J_goodsList");
        Elements lis = goodsList.getElementsByClass("gl-item");
        for (Element li : lis) {
            GoodInfo goodInfo = new GoodInfo();
            Random c=new Random();
            int random_num=c.nextInt(3);
            String img = li.getElementsByTag("img").eq(0).attr("src");
            String price = li.getElementsByClass("p-price").eq(0).text();
            String name = li.getElementsByClass("p-name").eq(0).text();
            goodInfo.setGimg(img);
            goodInfo.setGprice(price);
            goodInfo.setGname(name);
            switch(random_num){
                case 1 :
                    goodInfo.setGtype("Down");

                    break; //可选
                case 2 :
                    goodInfo.setGtype("Appliance");
                    break; //可选

                default : //可选
                    goodInfo.setGtype("Daily");
                    //语句
            }
            goodInfos.add(goodInfo);
        }
//        for (GoodInfo goodInf : goodInfos) {
//            System.out.println("==============================");
//            System.out.println(goodInf);
//        }
        return goodInfos;

    }
}

